/**
 * 
 */
package com.yqwh.coder.handlerphoto;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.UUID;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.commons.CommonsMultipartFile;



/**
 * @author hejie
 * @date  2018年3月21日
 */
public class Main {
	final static Logger logger = LoggerFactory.getLogger(Main.class);
	/**
	 * 对图片上传进行等比例压缩处理
	 * 
	 * @param savePath
	 * @param extendname
	 * @param inputStream
	 * @return
	 */
	public String uploadFile(CommonsMultipartFile file1) {
		try {
			String uploadExt = appProps.getProperty("photo.uploadExt");
			if (file1.getFileItem().getSize() > 5 * 1024 * 1024) {// 上传文件大小不能超过5M
				return "-1001";// 上传文件大小超过5M,直接返回
			}
			ImageInputStream imageInputStream = ImageIO.createImageInputStream(file1.getInputStream());
			Iterator<ImageReader> iterator = ImageIO.getImageReaders(imageInputStream);
			String extendname = "";
			while (iterator.hasNext()) {
				ImageReader reader = iterator.next();
				extendname = reader.getFormatName();// 获取上传文件的扩展名
			}
			if ("".equals(extendname) || uploadExt.indexOf(extendname.toLowerCase()) < 0) {
				return "-1002";// 格式不对,只支持jpeg/jpg
			}
			String savePath = appProps.getProperty("activitypath");
			File path = new File(savePath);
			if (!path.exists()) {
				path.mkdirs();//文件不存在，创建
			}
			String fileName = UUID.randomUUID().toString() + "." + extendname.toLowerCase();//定义广告位文件名
			File file2 = new File(savePath + fileName);
			BufferedImage bufferedImage = ImageIO.read(file1.getInputStream());
			ImageIO.write(bufferedImage, extendname.toLowerCase(), file2);//文件创建
			ImageUtils.newCreateIconSmall(file2.getPath(), savePath, "thumb_"+fileName, 200, 200);
			return fileName;//操作成功返回文件名称
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return "-1";//操作失败
		} finally {
			try {
				file1.getInputStream().close();
			} catch (IOException e) {
				logger.error(e.getMessage(), e);
			}
		}
	}
}
